package com.imonsoft.sqm.web.business.ipic_system;

import java.awt.*;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.sqm.pojo.basedata.Dictionary;
import com.imonsoft.sqm.pojo.business.ipic_system.Claim;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.business.ipic_system.ClaimService;
import com.imonsoft.sqm.service.business.ipic_system.IncomingService;
import com.imonsoft.sqm.vo.business.ipic_system.PPMVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/business/ipic_system/ppm_pie")
public class PPMPieController {
	protected final Log logger = LogFactory.getLog(getClass());
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private ClaimService claimService;
    @Autowired
    private IncomingService incomingService;

    @RequestMapping("/listUI.do")
    public void listUI(ModelMap model,HttpSession session,PPMVo ppmVo) {
        if(StringUtils.isEmpty(ppmVo.getYear())){
            ppmVo.setYear(DateUtil.getNowDate().substring(0,4));
        }
        if(StringUtils.isEmpty(ppmVo.getMonth())){
            ppmVo.setMonth(DateUtil.getNowDate().substring(5, 7));
        }
        model.put("entity", ppmVo);
        //按照来料、车间、顾客发生的PPM形成百分比饼图（按照不合格品报告抓取数据）当月发生次数百分比
        Map<String,Integer> resultMap1=new HashMap<String,Integer>();
        List<Dictionary> dictionaryList=dictionaryService.findDictionaryByType(ConstantDict.FIND_PLACE);
        for(Dictionary dictionary:dictionaryList){
            List<Claim> claimList=claimService.getClaimListByYearAndMonthAndFindPlace(ppmVo.getYear(), ppmVo.getMonth(), dictionary.getCode());
            /*int total=0;
            for(Claim claim:claimList){
                total=total+claim.getAmountNotQualified();
            }*/
            resultMap1.put(dictionary.getName(),claimList.size());
        }
        //按照发生问题的原因分解总PPM为物流原因导致还是质量原因导致形成百分比饼图（按照PPM种类抓取数据）当月

        int incomingTotal=incomingService.findIncomingTotalByYearAndMonth(ppmVo.getYear(), ppmVo.getMonth());
        List<Claim> logisticClaimList=claimService.findClaimByYearAndMonthAndClaimType(ppmVo.getYear(), ppmVo.getMonth(), ConstantSqm.CLAIM_TYPE_LOGISTIC);
        List<Claim> technicalClaimList=claimService.findClaimByYearAndMonthAndClaimType(ppmVo.getYear(), ppmVo.getMonth(), ConstantSqm.CLAIM_TYPE_TECHNICAL);
        Map<String,Integer> resultMap2=new HashMap<String,Integer>();
        if(null!=logisticClaimList){
            int total=0;
            for(Claim claim:logisticClaimList){
                total=total+claim.getAmountNotQualified();
            }
            int ppm=0;
            if(incomingTotal!=0){
                ppm=total*1000000/incomingTotal;
            }
            resultMap2.put("物流原因",ppm);
        }
        if(null!=technicalClaimList){
            int total=0;
            for(Claim claim:technicalClaimList){
                total=total+claim.getAmountNotQualified();
            }
            int ppm=0;
            if(incomingTotal!=0){
                ppm=total*1000000/incomingTotal;
            }
            resultMap2.put("质量原因",ppm);
        }

        model.put("imagePath1",drawToJSP(session, createChart(createDataSet(resultMap1))));
        model.put("imagePath2",drawToJSP(session, createChart(createDataSet(resultMap2))));
    }
    /**
     * step1:创建数据集对象
     * @return
     */
    public static PieDataset createDataSet(Map<String,Integer> resultMap) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        Set<String> key = resultMap.keySet();
        for (Iterator iterator = key.iterator(); iterator.hasNext();) {
            String keyStr=(String)iterator.next();
            dataset.setValue(keyStr,resultMap.get(keyStr));
        }

        return dataset;
    }

    /**
     * step2:创建图表
     * @param dataset
     * @return
     */
    public static JFreeChart createChart(PieDataset dataset) {
        JFreeChart chart = ChartFactory.createPieChart(
                "", // 图表标题
                dataset, // 数据集
                true, // 是否显示图例
                true, // 是否显示工具提示
                true // 是否生成URL
        );

        //设置标题字体==为了防止中文乱码：必须设置字体
        chart.setTitle(new TextTitle("", new Font("黑体", Font.ITALIC, 22)));
        //设置图例的字体==为了防止中文乱码：必须设置字体
        chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 22));
        // 获取饼图的Plot对象(实际图表)
        PiePlot plot = (PiePlot) chart.getPlot();
        //图形边框颜色
        plot.setBaseSectionOutlinePaint(Color.GRAY);
        // 设置柱图背景色（注意，系统取色的时候要使用16位的模式来查看颜色编码，这样比较准确）
        plot.setBackgroundPaint(new Color(255, 255, 204));
        //图形边框粗细
        plot.setBaseSectionOutlineStroke(new BasicStroke(0.0f));
        //设置饼状图的绘制方向，可以按顺时针方向绘制，也可以按逆时针方向绘制
        plot.setDirection(Rotation.ANTICLOCKWISE);
        //设置绘制角度(图形旋转角度)
        plot.setStartAngle(70);
        //设置突出显示的数据块
        plot.setExplodePercent("One", 0.1D);
        //设置背景色透明度
        plot.setBackgroundAlpha(0.7F);
        // 设置前景色透明度
        plot.setForegroundAlpha(0.65F);
        //设置区块标签的字体==为了防止中文乱码：必须设置字体
        plot.setLabelFont(new Font("隶书", Font.PLAIN, 22));
        // 图例显示百分比:自定义方式，{0} 表示选项， {1} 表示数值， {2} 表示所占比例 ,小数点后两位
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
                "{0}:{1}({2})", NumberFormat.getNumberInstance(),
                new DecimalFormat("0.00%")));
        // 图例显示百分比
        // plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
        // 指定显示的饼图为：圆形(true) 还是椭圆形(false)
        plot.setCircular(false);
        // 没有数据的时候显示的内容
        plot.setNoDataMessage(ConstantSqm.DATA_NOTHING);
        return chart;
    }

    /**
     * step3: 输出图表到tomcat临时目录
     * @param session
     * @param chart
     */
    private String drawToJSP(HttpSession session,JFreeChart chart){
        String url ="";
        try {
            String fileName = ServletUtilities.saveChartAsPNG(chart, 800, 600, session);
            //ServletUtilities是面向web开发的工具类，返回一个字符串文件名,文件名自动生成，生成好的图片会自动放在服务器（tomcat）的临时文件下（temp）

            url = "/DisplayChart?filename=" + fileName;
            //根据文件名去临时目录下寻找该图片，这里的/DisplayChart路径要与配置文件里用户自定义的<url-pattern>一致
        }catch (SystemException se) {
            logger.info(se.getMessage());
        }catch (IOException e) {
            logger.error(e.getMessage());
        }catch (Exception e) {
            logger.error(e.getMessage());
        }
        return url;
    }
}
